package handler

import (
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
	v1 "server_go/api/v1"
	"server_go/internal/service"
	"strconv"
)

type ArticleHandler struct {
	*Handler
	articleService service.ArticleService
}

func NewArticleHandler(
	handler *Handler,
	articleService service.ArticleService,
) *ArticleHandler {
	return &ArticleHandler{
		Handler:        handler,
		articleService: articleService,
	}
}

func (h *ArticleHandler) GetArticle(ctx *gin.Context) {
}

func (h *ArticleHandler) DeleteArticle(ctx *gin.Context) {

	articleId := ctx.Param("articleId")
	if articleId == "" {
		err := errors.New("文章 ID 不能为空")
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}

	article, err := strconv.Atoi(articleId)
	userType := GetUserTypeFromCtx(ctx)
	userId := GetUserIdFromCtx(ctx)
	err = h.articleService.DeleteArticle(ctx, uint(article), userId, userType)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}

	v1.HandleSuccess(ctx, nil)
}
func (h *ArticleHandler) CreateArticle(ctx *gin.Context) {
	req := new(v1.CreateArticleRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	err := h.articleService.CreateArticle(ctx, *req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}
func (h *ArticleHandler) GetArticles(ctx *gin.Context) {
	//userType := GetUserTypeFromCtx(ctx)
	//if userType != 1 {
	//	v1.HandleError(ctx, http.StatusForbidden, v1.ErrTypeNotfound, nil)
	//	return
	//}
	articles, err := h.articleService.GetArticles(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, articles)
}

func (h *ArticleHandler) GetArticlesByUserId(ctx *gin.Context) {
	// 从 URL 路径参数获取 userId
	userIdStr := ctx.Param("userId")
	userId, err := strconv.ParseUint(userIdStr, 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "invalid userId",
		})
		return
	}

	// 调用 service
	articles, err := h.articleService.GetArticlesByUserId(ctx, uint(userId))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 成功返回
	ctx.JSON(http.StatusOK, gin.H{
		"data": articles,
	})
}
func (h *ArticleHandler) GetArticlesByTagID(ctx *gin.Context) {
	tagIDStr := ctx.Param("tagId")
	tagID, err := strconv.ParseUint(tagIDStr, 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid tagId"})
		return
	}

	articles, err := h.articleService.GetArticlesByTagID(ctx, uint(tagID))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"data": articles})
}
